#pragma once

#include <iostream>
#include <vector>
#include <unistd.h>
#include <sys/wait.h>
#include "task.hpp"
class Channel
{
public:
    Channel(pid_t pid, int fd) : _wfd(fd), _subid(pid)
    {
        _name = "channel-" + std::to_string(fd) + "-" + std::to_string(pid);
    }

    std::string GetName()
    {
        return _name;
    }

    void Send(int code)
    {
        int n = write(_wfd, &code, sizeof(code));
        (void)n;
    }

    void Close()
    {
        close(_wfd);
    }

    void Wait()
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }

    ~Channel() {}

private:
    int _wfd;
    int _subid;
    std::string _name;
};

class ChannelManager
{
public:
    ChannelManager() : _next(0)
    {
    }

    bool Insert(pid_t pid, int fd)
    {
        _channels.push_back({pid, fd});
    }

    void Print()
    {
        for (auto &channel : _channels)
        {
            std::cout << channel.GetName() << std::endl;
        }
    }

    Channel &Select()
    {
        Channel &c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }

    void StopSubProcess()
    {
        for (auto &channel : _channels)
        {
            channel.Close();
            std::cout << "关闭: " << channel.GetName() << std::endl;
        }
    }

    void WaitSubProcess()
    {
        for (auto &channel : _channels)
        {
            channel.Wait();
            std::cout << "回收: " << channel.GetName() << std::endl;
        }
    }

    void StopAndWait()
    {
        for (auto &channel : _channels)
        {
            channel.Close();
            std::cout << "关闭: " << channel.GetName() << std::endl;
            channel.Wait();
            std::cout << "回收: " << channel.GetName() << std::endl;
        }
    }

    ~ChannelManager() {}

private:
    std::vector<Channel> _channels;
    int _next;
};

class ProcessPool
{
public:
    ProcessPool(int num) : _process_num(num)
    {
        _tm.Register(PrintLog);
        _tm.Register(Download);
        _tm.Register(Upload);
    }

    void Work(int rfd)
    {
        while (true)
        {
            int task_code = 0;
            int n = read(rfd, &task_code, sizeof(task_code));
            if (n > 0)
            {
                // 执行任务
                _tm.Execute(task_code);
            }
            else if (n == 0)
            {
                std::cout << "子进程退出" << std::endl;
                break;
            }
            else
            {
                std::cout << "读取错误" << std::endl;
                break;
            }
        }
    }

    bool Start()
    {
        // 创建_process_num个管道
        for (int i = 0; i < _process_num; i++)
        {
            // 创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return false;

            // 创建子进程
            pid_t id = fork();
            if (id < 0)
                return false;
            else if (id == 0)
            {
                // 子进程
                close(pipefd[1]);
                Work(pipefd[0]);
                close(pipefd[0]);
                exit(0);
            }
            else
            {
                // 父进程
                close(pipefd[0]);
                _cm.Insert(id, pipefd[1]);
            }
        }
        return true;
    }

    void Run()
    {
        // 选择一个任务
        int taskcode = _tm.Code();

        // 选择一个信道[子进程]，用轮询的方式
        Channel &c = _cm.Select();
        c.Send(taskcode);
        std::cout << "选择子进程" << c.GetName() << "-任务码：" << taskcode << std::endl;
    }

    void Stop()
    {
        _cm.StopSubProcess();
        _cm.WaitSubProcess();
        //_cm.StopAndWait();
    }

    void Debug()
    {
        _cm.Print();
    }

    ~ProcessPool() {}

private:
    ChannelManager _cm;
    int _process_num;
    TaskManager _tm;
};